package 多线程.AQS;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class Mutex {
    private static class Sync extends AbstractQueuedSynchronizer {
        // 当state为0时，表示锁没有被占用；当为1时，表示锁已被占用
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        // 尝试获取锁，如果state为0，则获取成功；否则加入等待队列
        public boolean tryAcquire(int acquires) {
            assert acquires == 1; // Otherwise unused
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        // 释放锁
        protected boolean tryRelease(int releases) {
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }
    }

    // 创建一个Sync对象作为锁
    private final Sync sync = new Sync();

    // 获取锁
    public void lock() {
        sync.acquire(1);
    }

    // 释放锁
    public void unlock() {
        sync.release(1);
    }
}

